package day0114

import (
	"math"
	"sort"
)

func threeSumClosest(nums []int, target int) int {
	n := len(nums)
	min := 0
	r := math.MaxInt64
	sort.Ints(nums)
	for i := 0; i < n-2; i++ {
		left, right := i+1, n-1
		for left < right {
			tmp := nums[i] + nums[left] + nums[right]
			if abs(target-tmp) < r {
				min = tmp
				r = abs(target - tmp)
			}
			if tmp < target {
				left++
			} else {
				right--
			}
		}
	}
	return min
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
